package com.hfb.mashibing.alip8.designpattern._018command;

/**
 * 命令模式 的undo 经常和 责任链 结合使用
 */
public class MianV1 {
    public static void main(String[] args) {
        Context c = new Context();

        Command insertCommand = new InsertCommand(c);
        insertCommand.doit();
        insertCommand.undo();

        Command copyCommand = new CopyCommand(c);
        copyCommand.doit();
        copyCommand.undo();

        Command delCommand = new DeleteCommand(c);
        delCommand.doit();
        delCommand.undo();

        System.err.println(c.msg);
    }

    static class Context {
        String msg = "hello everybody";
    }
    static abstract class Command {
        public abstract void doit(); // exec or run
        public abstract void undo();
    }
    static class InsertCommand extends Command {
        Context c;
        String strToInsert = "http://www.mashibing.com";
        public InsertCommand(Context c) {
            this.c = c;
        }
        @Override
        public void doit(){c.msg += strToInsert;}
        @Override
        public void undo(){c.msg = c.msg.substring(0,c.msg.length()-strToInsert.length());}
    }
    static class CopyCommand extends Command {
        Context c;
        public CopyCommand(Context c) {
            this.c = c;
        }
        @Override
        public void doit(){c.msg += c.msg;}
        @Override
        public void undo(){c.msg = c.msg.substring(0, c.msg.length()/2);}
    }
    static class DeleteCommand extends Command {
        Context c;
        String delStr;
        public DeleteCommand(Context c) {
            this.c = c;
        }
        @Override
        public void doit(){
            delStr = c.msg.substring(0, 5);
            c.msg = c.msg.substring(5);
        }
        @Override
        public void undo(){ c.msg = delStr + c.msg; }
    }

}

